package com.tanhua.sso.controller;


import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {


    @Autowired
    private UserService userService;

    @RequestMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String,String> param){

        try {
            String phone = param.get("phone");
            String verificationCode = param.get("verificationCode");

            String data = userService.login(phone,verificationCode);

            if(!StringUtils.isEmpty(data)) {
                //不为空表示登录成功

                Map<String,Object> result = new HashMap<>(2);

                String[] ss = StringUtils.split(data, "|");
                result.put("token",ss[0]);
                result.put("isNew",Boolean.valueOf(ss[1]));
                //返回响应200及结果
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {

            log.error("登录失败!!",e);

        }

        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("登录失败！").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);

    }


}
